package protomysql

import (
	"strconv"

	"gitee.com/crack007/proxy/src/config"
	"gitee.com/crack007/proxy/src/proxy/protocol/logdump"

	"gitee.com/crack007/goose/gscore/server"
	"gitee.com/crack007/goose/gslog"
)

type Mysql struct {
	Session     *server.Session
	MysqlClient *MysqlClient
	MysqlServer *MysqlServer
}

// 处理从client端返回的数据
func (s *Mysql) ProcessClient(data []byte) {
	defer func() {
		err := recover()
		if err != nil {
			gslog.Error(err)
		}
	}()
	s.MysqlClient.Process(data, s)
}

// 处理从服务端返回的数据
func (s *Mysql) ProcessServer(serverSession *server.Client, data []byte) {
	defer func() {
		err := recover()
		if err != nil {
			gslog.Error(err)
		}
	}()
	s.MysqlServer.Process(data, s)
}

func (s *Mysql) DumpSql(sql string, isSlow bool) {
	if isSlow {
		logdump.Warn("[%s][%s][SLOW] [%s] %s", s.GetSessionId(), s.MysqlClient.GetCostTimeLabel(), s.MysqlClient.HandshakeResponse41.Database, sql)
		return
	}
	costTime := ""
	if config.MysqlConfig.ShowCostTime {
		costTime = "[" + s.MysqlClient.GetCostTimeLabel() + "]"
	}
	//dmlList := []string{"INSERT", "DELETE", "UPDATE"}
	//for _, dml := range dmlList {
	//	if strings.HasPrefix(strings.TrimSpace(strings.ToUpper(sql)), dml) {
	//		sql = addDmlTag(dml, sql)
	//		break
	//	}
	//}
	logdump.Info("[%s]%s [%s] %s", s.GetSessionId(), costTime, s.MysqlClient.HandshakeResponse41.Database, sql)
}

func (s *Mysql) GetSessionId() string {
	if s.MysqlServer.handshakeV10 != nil {
		return strconv.Itoa(s.MysqlServer.handshakeV10.ThreadId)
	}
	return s.Session.RemoteIp + ":" + strconv.Itoa(int(s.Session.RemotePort))
}

func (s *Mysql) Init(session *server.Session) {
	s.Session = session
}

func (s *Mysql) Reset() {
	s.MysqlClient.Reset()
	s.MysqlServer.Reset()
}
